// 所有功能在DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 导航栏交互
    const hamburger = document.querySelector('.hamburger');
    const navLinks = document.querySelector('.nav-links');
    
    if (hamburger && navLinks) {
        hamburger.addEventListener('click', () => {
            navLinks.classList.toggle('active');
        });
    }
    
    // 设置当前日期
    const dateElement = document.querySelector('.date');
    if (dateElement) {
        const now = new Date();
        const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
        dateElement.textContent = now.toLocaleDateString('zh-CN', options);
    }
    
    // Tab切换功能
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            // 移除同组所有按钮的active类
            const parentContainer = button.closest('.category-tabs') || button.closest('.community-tabs');
            if (parentContainer) {
                parentContainer.querySelectorAll('.tab-btn').forEach(btn => {
                    btn.classList.remove('active');
                });
            }
            
            // 给当前按钮添加active类
            button.classList.add('active');
            
            // 这里可以添加加载对应内容的逻辑
            // 模拟加载效果
            const container = button.closest('section');
            if (container) {
                const loading = document.createElement('div');
                loading.className = 'loading';
                loading.textContent = '加载中...';
                loading.style.textAlign = 'center';
                loading.style.padding = '20px';
                loading.style.color = '#636e72';
                
                const contentArea = container.querySelector('.articles-list') || container.querySelector('.community-posts');
                if (contentArea) {
                    // 模拟内容更新
                    setTimeout(() => {
                        // 这里仅做演示，实际项目中应该加载对应的数据
                    }, 500);
                }
            }
        });
    });

    // 分类卡片点击事件
    const categoryCards = document.querySelectorAll('.category-card');
    categoryCards.forEach(card => {
        card.addEventListener('click', () => {
            // 模拟分类点击效果
            categoryCards.forEach(c => c.classList.remove('active'));
            card.classList.add('active');
            
            // 这里可以添加加载对应分类文章的逻辑
            const articlesSection = document.querySelector('.recommended-articles');
            if (articlesSection) {
                const loading = document.createElement('div');
                loading.className = 'loading';
                loading.textContent = `正在加载「${card.querySelector('span').textContent}」相关文章...`;
                loading.style.textAlign = 'center';
                loading.style.padding = '40px';
                loading.style.color = '#636e72';
                loading.style.fontSize = '16px';
                
                const articlesList = articlesSection.querySelector('.articles-list');
                if (articlesList) {
                    articlesList.innerHTML = '';
                    articlesList.appendChild(loading);
                    
                    // 模拟加载延迟
                    setTimeout(() => {
                        // 恢复原来的文章列表
                        // 实际项目中应该根据分类加载对应文章
                        location.reload(); // 这里仅做演示，实际应该动态更新内容
                    }, 1000);
                }
            }
        });
    });

    // 查看更多按钮点击事件
    const loadMoreBtn = document.querySelector('.load-more');
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', () => {
            loadMoreBtn.textContent = '加载中...';
            loadMoreBtn.disabled = true;
            
            // 模拟加载更多文章
            setTimeout(() => {
                loadMoreBtn.textContent = '没有更多了';
                loadMoreBtn.classList.add('disabled');
            }, 1500);
        });
    }

    // 文章项点击事件
    const articleItems = document.querySelectorAll('.article-item');
    articleItems.forEach(item => {
        item.addEventListener('click', (e) => {
            // 阻止冒泡，避免点击链接时触发整个卡片的点击事件
            if (e.target.tagName === 'A') return;
            
            // 模拟文章详情跳转
            const articleTitle = item.querySelector('h4').textContent;
            alert(`您正在查看文章：${articleTitle}\n\n实际项目中这里应该跳转到文章详情页`);
        });
    });

    // 社区帖子点击事件
    const postItems = document.querySelectorAll('.post-item');
    postItems.forEach(item => {
        item.addEventListener('click', (e) => {
            // 阻止冒泡，避免点击链接时触发整个卡片的点击事件
            if (e.target.tagName === 'A') return;
            
            // 模拟帖子详情跳转
            const postTitle = item.querySelector('.post-content h4').textContent;
            alert(`您正在查看帖子：${postTitle}\n\n实际项目中这里应该跳转到帖子详情页`);
        });
    });

    // 创建新帖按钮点击事件
    const createPostBtn = document.querySelector('.create-post-btn');
    if (createPostBtn) {
        createPostBtn.addEventListener('click', () => {
            alert('请先登录后发布新帖！\n\n实际项目中这里应该跳转到登录页面或显示登录弹窗');
        });
    }

    // Newsletter表单提交
    const newsletterForm = document.querySelector('.newsletter-form');
    if (newsletterForm) {
        newsletterForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const emailInput = newsletterForm.querySelector('input[type="email"]');
            const dateInput = newsletterForm.querySelector('input[type="text"]');
            
            if (emailInput && dateInput) {
                const email = emailInput.value;
                const birthDate = dateInput.value;
                
                // 简单的邮箱验证
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    alert('请输入有效的邮箱地址！');
                    return;
                }
                
                // 简单的日期验证
                const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
                if (!dateRegex.test(birthDate)) {
                    alert('请输入有效的出生日期格式（YYYY-MM-DD）！');
                    return;
                }
                
                alert(`订阅成功！\n邮箱：${email}\n宝宝出生日期：${birthDate}\n\n实际项目中这里应该发送订阅请求到服务器`);
                newsletterForm.reset();
            }
        });
    }

    // APP上线提醒表单提交
    const appNotifyForm = document.querySelector('.app-notify-form');
    if (appNotifyForm) {
        appNotifyForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const emailInput = appNotifyForm.querySelector('input[type="email"]');
            if (emailInput) {
                const email = emailInput.value;
                
                // 简单的邮箱验证
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    alert('请输入有效的邮箱地址！');
                    return;
                }
                
                alert(`提醒设置成功！我们将在APP上线时通知您：${email}\n\n实际项目中这里应该发送请求到服务器`);
                appNotifyForm.reset();
            }
        });
    }

    // 登录和注册按钮点击事件
    const loginBtn = document.querySelector('.login-btn');
    const registerBtn = document.querySelector('.register-btn');
    
    if (loginBtn) {
        loginBtn.addEventListener('click', () => {
            alert('登录功能开发中...\n\n实际项目中这里应该显示登录弹窗或跳转到登录页面');
        });
    }
    
    if (registerBtn) {
        registerBtn.addEventListener('click', () => {
            alert('注册功能开发中...\n\n实际项目中这里应该显示注册弹窗或跳转到注册页面');
        });
    }

    // 平滑滚动
    const smoothScrollLinks = document.querySelectorAll('a[href^="#"]');
    smoothScrollLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            
            const targetId = link.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80, // 减去导航栏高度
                    behavior: 'smooth'
                });
            }
        });
    });

    // 页面加载完成后的动画效果
    
    // 添加元素入场动画
    const animateElements = document.querySelectorAll('.hero-content, .topic-card, .feature-card, .article-item');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, { threshold: 0.1 });
    
    animateElements.forEach(element => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(20px)';
        element.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        observer.observe(element);
    });
    
    // 初始化聊天窗口状态
    const chatContainer = document.getElementById('chat-container');
    const chatToggleIcon = document.getElementById('chat-toggle-icon');
    
    if (chatContainer && chatToggleIcon) {
        chatContainer.style.display = 'none';
        chatToggleIcon.classList.add('fa-chevron-up');
        chatToggleIcon.classList.remove('fa-chevron-down');
    }

    // 首页CTA按钮点击事件
    const primaryBtn = document.querySelector('.primary-btn');
    const secondaryBtn = document.querySelector('.secondary-btn');
    
    if (primaryBtn) {
        primaryBtn.addEventListener('click', () => {
            // 立即体验按钮 - 打开聊天窗口
            if (window.toggleChat) {
                window.toggleChat();
            }
        });
    }
    
    if (secondaryBtn) {
        secondaryBtn.addEventListener('click', () => {
            // 了解更多按钮 - 滚动到功能介绍
            const featuresSection = document.getElementById('features');
            if (featuresSection) {
                window.scrollTo({
                    top: featuresSection.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    }
    
    // 专题卡片点击事件
    const topicCards = document.querySelectorAll('.topic-card');
    topicCards.forEach(card => {
        card.addEventListener('click', () => {
            const topicTitle = card.querySelector('h3').textContent;
            alert(`您正在查看专题：${topicTitle}\n\n实际项目中这里应该跳转到专题详情页`);
        });
    });
    
    // 功能卡片点击事件
    const featureCards = document.querySelectorAll('.feature-card');
    featureCards.forEach(card => {
        card.addEventListener('click', () => {
            const featureTitle = card.querySelector('h3').textContent;
            alert(`功能详情：${featureTitle}\n\n${card.querySelector('p').textContent}`);
        });
    });
}); // 结束DOMContentLoaded事件监听器

    // 响应式导航栏处理
    window.addEventListener('resize', () => {
        if (window.innerWidth > 768 && navLinks) {
            navLinks.classList.remove('active');
        }
    });

    // 返回顶部按钮功能
    function setupBackToTop() {
        const backToTopButton = document.createElement('button');
        backToTopButton.className = 'back-to-top';
        backToTopButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
        backToTopButton.style.cssText = `
            position: fixed;
            bottom: 20px;
            left: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #ff6b6b;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.3s ease;
            transform: translateY(20px);
            z-index: 999;
            box-shadow: 0 4px 10px rgba(255, 107, 107, 0.3);
        `;
        
        document.body.appendChild(backToTopButton);
        
        window.addEventListener('scroll', () => {
            if (window.scrollY > 300) {
                backToTopButton.style.opacity = '1';
                backToTopButton.style.transform = 'translateY(0)';
            } else {
                backToTopButton.style.opacity = '0';
                backToTopButton.style.transform = 'translateY(20px)';
            }
        });
        
        backToTopButton.addEventListener('click', () => {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }

    // 调用返回顶部按钮设置
    setupBackToTop();
    
    // 修复今日育儿Tip查看详情链接
    const readMoreLink = document.querySelector('.read-more');
    if (readMoreLink) {
        readMoreLink.addEventListener('click', (e) => {
            e.preventDefault();
            alert('查看完整的育儿Tip详情！\n\n实际项目中这里应该跳转到详情页面');
        });
    }

    // 登录和注册功能
    const loginModal = document.getElementById('login-modal');
    const registerModal = document.getElementById('register-modal');
    const loginBtn = document.querySelector('.login-btn');
    const registerBtn = document.querySelector('.register-btn');
    const closeModalBtns = document.querySelectorAll('.close-modal');
    const modalOverlays = document.querySelectorAll('.modal-overlay');
    const switchToRegisterLinks = document.querySelectorAll('.switch-to-register');
    const switchToLoginLinks = document.querySelectorAll('.switch-to-login');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');

    // 显示模态框
    function showModal(modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden'; // 防止背景滚动
    }

    // 隐藏模态框
    function hideModal(modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }

    // 隐藏所有模态框
    function hideAllModals() {
        hideModal(loginModal);
        hideModal(registerModal);
    }

    // 事件监听器
    if (loginBtn) {
        loginBtn.addEventListener('click', () => showModal(loginModal));
    }

    if (registerBtn) {
        registerBtn.addEventListener('click', () => showModal(registerModal));
    }

    // 关闭按钮事件
    closeModalBtns.forEach(btn => {
        btn.addEventListener('click', hideAllModals);
    });

    // 点击遮罩层关闭模态框
    modalOverlays.forEach(overlay => {
        overlay.addEventListener('click', hideAllModals);
    });

    // 切换到注册
    switchToRegisterLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            hideModal(loginModal);
            showModal(registerModal);
        });
    });

    // 切换到登录
    switchToLoginLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            hideModal(registerModal);
            showModal(loginModal);
        });
    });

    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            
            // 简单验证
            if (!email || !password) {
                alert('请填写完整的登录信息');
                return;
            }
            
            // 模拟登录请求
            console.log('登录请求:', { email, password });
            
            // 从本地存储获取用户名，如果没有则使用邮箱前缀
            let userName = localStorage.getItem('userName');
            if (!userName) {
                userName = email.split('@')[0];
            }
            
            // 模拟登录成功
            alert(`登录成功！欢迎回来，${userName}！\n\n实际项目中这里应该发送请求到服务器进行身份验证`);
            hideAllModals();
            
            // 模拟更新用户状态
            updateUserStatus(true, userName);
        });
    }

    // 注册表单提交
    if (registerForm) {
        registerForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const name = document.getElementById('register-name').value;
            const email = document.getElementById('register-email').value;
            const password = document.getElementById('register-password').value;
            const confirmPassword = document.getElementById('register-confirm').value;
            const babyBirthday = document.getElementById('baby-birthday').value;
            
            // 简单验证
            if (!name || !email || !password || !confirmPassword) {
                alert('请填写完整的注册信息');
                return;
            }
            
            if (password !== confirmPassword) {
                alert('两次输入的密码不一致');
                return;
            }
            
            // 密码强度检查
            if (password.length < 6) {
                alert('密码长度至少为6位');
                return;
            }
            
            // 保存用户信息到本地存储
            localStorage.setItem('userName', name);
            localStorage.setItem('userEmail', email);
            
            // 模拟注册请求
            console.log('注册请求:', { name, email, password, babyBirthday });
            
            // 模拟注册成功
            alert(`注册成功！欢迎您，${name}！请使用您的账号登录。\n\n实际项目中这里应该发送请求到服务器进行注册`);
            hideModal(registerModal);
            showModal(loginModal);
        });
    }

    // 生成随机宝宝头像
    function generateBabyAvatar() {
        // 宝宝头像类型：0-男孩，1-女孩，2-婴儿（中性）
        const avatarType = Math.floor(Math.random() * 3);
        
        // 根据类型生成不同的头像样式
        let avatarColor, avatarFace, avatarAccessory;
        
        // 随机颜色
        const colors = ['#FF9E9E', '#FFD89E', '#E8FF9E', '#9EFFD8', '#9EB8FF', '#D89EFF', '#FF9ED8'];
        avatarColor = colors[Math.floor(Math.random() * colors.length)];
        
        // 根据类型生成面部特征
        switch(avatarType) {
            case 0: // 男孩
                avatarFace = `<circle cx="25" cy="30" r="15" fill="${avatarColor}"></circle>
                              <circle cx="20" cy="25" r="2" fill="#333"></circle>
                              <circle cx="30" cy="25" r="2" fill="#333"></circle>
                              <path d="M20 35 Q25 40 30 35" stroke="#333" stroke-width="1" fill="none"></path>
                              <path d="M18 20 Q15 15 18 10" stroke="#333" stroke-width="1" fill="none"></path>
                              <path d="M32 20 Q35 15 32 10" stroke="#333" stroke-width="1" fill="none"></path>`;
                break;
            case 1: // 女孩
                avatarFace = `<circle cx="25" cy="30" r="15" fill="${avatarColor}"></circle>
                              <circle cx="20" cy="25" r="2" fill="#333"></circle>
                              <circle cx="30" cy="25" r="2" fill="#333"></circle>
                              <path d="M20 35 Q25 40 30 35" stroke="#333" stroke-width="1" fill="none"></path>
                              <path d="M15 25 Q10 10 25 10 Q40 10 35 25" stroke="#FF6B6B" stroke-width="1" fill="#FFB6C1"></path>`;
                break;
            case 2: // 婴儿
                avatarFace = `<circle cx="25" cy="30" r="15" fill="${avatarColor}"></circle>
                              <circle cx="20" cy="25" r="2" fill="#333"></circle>
                              <circle cx="30" cy="25" r="2" fill="#333"></circle>
                              <path d="M20 35 Q25 40 30 35" stroke="#333" stroke-width="1" fill="none"></path>
                              <circle cx="25" cy="15" r="3" fill="#FFB6C1"></circle>`;
                break;
        }
        
        // 随机添加配饰
        const accessories = [
            '', // 无配饰
            `<circle cx="25" cy="25" r="18" fill="none" stroke="#8B4513" stroke-width="1"></circle>`, // 帽子
            `<path d="M15 35 L35 35" stroke="#FFD700" stroke-width="1"></path>`, // 项链
            `<rect x="15" y="25" width="20" height="5" rx="2" fill="#333"></rect>` // 围兜
        ];
        avatarAccessory = accessories[Math.floor(Math.random() * accessories.length)];
        
        // 返回完整的SVG头像
        return `<svg width="50" height="50" viewBox="0 0 50 50">
                    ${avatarFace}
                    ${avatarAccessory}
                </svg>`;
    }

    // 更新用户状态（登录/登出后）
    function updateUserStatus(isLoggedIn, userName = '用户') {
        const userActions = document.querySelector('.user-actions');
        if (userActions) {
            if (isLoggedIn) {
                // 生成随机宝宝头像
                const babyAvatar = generateBabyAvatar();
                
                userActions.innerHTML = `
                    <div class="user-profile">
                        <div class="user-avatar" title="${userName}">
                            ${babyAvatar}
                        </div>
                        <span class="user-name">${userName}</span>
                        <button class="btn logout-btn">登出</button>
                    </div>
                `;
                
                // 添加登出按钮事件
                const logoutBtn = document.querySelector('.logout-btn');
                if (logoutBtn) {
                    logoutBtn.addEventListener('click', () => {
                        updateUserStatus(false);
                        alert('已成功登出');
                    });
                }
            } else {
                userActions.innerHTML = `
                    <button class="btn login-btn">登录</button>
                    <button class="btn register-btn">注册</button>
                `;
                
                // 重新绑定登录和注册按钮事件
                const newLoginBtn = document.querySelector('.login-btn');
                const newRegisterBtn = document.querySelector('.register-btn');
                
                if (newLoginBtn) {
                    newLoginBtn.addEventListener('click', () => showModal(loginModal));
                }
                
                if (newRegisterBtn) {
                    newRegisterBtn.addEventListener('click', () => showModal(registerModal));
                }
            }
        }
    }
    
    // 添加ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            hideAllModals();
        }
    });